package com.moonbird.springboot.Utils.Qwen;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import javax.imageio.ImageIO;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.codec.binary.Base64;

public class ImageGeneratorUtil {

  private static final OkHttpClient CLIENT = new OkHttpClient();
  private static final String MODEL = "flux-schnell";
  private static final String SIZE = "1024*1024";

  public static String generateImageBase64(String prompt) throws ApiException, NoApiKeyException, IOException {
    Constants.apiKey = "sk-c91bee81e9ef4fd4abe43a61b8f38479";
    ImageSynthesis is = new ImageSynthesis();
    ImageSynthesisParam param =
            ImageSynthesisParam.builder()
                    .model(MODEL)
                    .size(SIZE)
                    .prompt(prompt)
                    .build();

    ImageSynthesisResult result = is.call(param);

    // Get the first image from the results and convert it to Base64.
    Map<String, String> item = result.getOutput().getResults().get(0);
    String imageUrl = item.get("url");

    Request request = new Request.Builder()
            .url(imageUrl)
            .build();

    try (Response response = CLIENT.newCall(request).execute()) {
      if (!response.isSuccessful()) {
        throw new IOException("Unexpected code " + response);
      }

      byte[] imageData = response.body().bytes();
      return Base64.encodeBase64String(imageData);
    }
  }

  public static void main(String[] args) {

  }
}